package day0727API;


public class Test3 {
    public static void main(String[] args) {
        Bank3  bank=new Bank3();
        Thread t1=new Thread(){
            public void run() {
                while(true){
                    bank.getMoney();//取款
                    int rs=bank.checkUserMoney();//查询余额
                    //System.out.println(rs);
                    try {
                        Thread.sleep(800);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Thread.yield();//让t1进入Runnable状态，让t2运行
                }
            }
        };
        t1.start();


        Thread t2=new Thread(()-> {
            while(true){
                bank.getMoney();//取款
                int rs=bank.checkUserMoney();//查询余额
               // System.out.println(rs);
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread.yield();//让t1进入Runnable状态，让t2运行
            }
        });
        t2.start();
    }

}


class Bank3{
    int userMoney=10;
    Object  o=new Object();    //synchronized: 确保某线程执行此方法时，其他线程不能此方法
    public  synchronized int  getMoney(){//取钱
            if(userMoney==0){
                throw new RuntimeException("不能再取钱了");
            }
            userMoney--;

            System.out.println(Thread.currentThread().getName()+":userMoney:"+userMoney);
            return 1;
    }
    public int checkUserMoney(){//查询余额
        return userMoney;
    }
}


